<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Zend_Test_PHPUnit_Db - Zend Framework Manual</title>

    <link href="../css/shCore.css" rel="stylesheet" type="text/css" />
    <link href="../css/shThemeDefault.css" rel="stylesheet" type="text/css" />
    <link href="../css/styles.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Zend Framework</h1>
<h2>Programmer's Reference Guide</h2>
<ul>
    <li><a href="../en/zend.test.phpunit.db.html">Inglês (English)</a></li>
    <li><a href="../pt-br/zend.test.phpunit.db.html">Português Brasileiro (Brazilian Portuguese)</a></li>
</ul>
<table width="100%">
    <tr valign="top">
        <td width="85%">
            <table width="100%">
                <tr>
                    <td width="25%" style="text-align: left;">
                    <a href="zend.test.phpunit.html">Zend_Test_PHPUnit</a>
                    </td>

                    <td width="50%" style="text-align: center;">
                        <div class="up"><span class="up"><a href="zend.test.html">Zend_Test</a></span><br />
                        <span class="home"><a href="manual.html">Guia de Refer&ecirc;ncia do Programador</a></span></div>
                    </td>

                    <td width="25%" style="text-align: right;">
                        <div class="next" style="text-align: right; float: right;"><a href="zend.text.html">Zend_Text</a></div>
                    </td>
                </tr>
            </table>
<hr />
<div id="zend.test.phpunit.db" class="section"><div class="info"><h1 class="title">Zend_Test_PHPUnit_Db</h1></div>
    

    <p class="para">
        Coupling of data-access and the domain model often requires the use of a database for
        testing purposes. But the database is persistent across different tests which leads to
        test results that can affect each other. Furthermore setting up the database to be able to
        run a test is quite some work. PHPUnit&#039;s Database extension simplifies testing with a
        database by offering a very simple mechanism to set up and teardown the database between
        different tests. This component extends the PHPUnit Database extension with Zend Framework
        specific code, such that writing database tests against a Zend Framework application is
        simplified.
    </p>

    <p class="para">
        Database Testing can be explained with two conceptual entities, DataSets and DataTables.
        Internally the PHPUnit Database extension can build up an object structure of a database,
        its tables and containing rows from configuration files or the real database content. This
        abstract object graph can then be compared using assertions. A common use-case in database
        testing is setting up some tables with seed data, then performing some operations, and
        finally asserting that the operated on database-state is equal to some predefined expected
        state. <span class="classname">Zend_Test_PHPUnit_Db</span> simplifies this task by allowing to
        generate DataSets and DataTables from existing <span class="classname">Zend_Db_Table_Abstract</span>
        or <span class="classname">Zend_Db_Table_Rowset_Abstract</span> instances.
    </p>

    <p class="para">
        Furthermore this component allows to integrate any
        <span class="classname">Zend_Db_Adapter_Abstract</span> for testing whereas the original extension
        only works with <acronym class="acronym">PDO</acronym>. A Test Adapter implementation for
        <span class="classname">Zend_Db_Adapter_Abstract</span> is also included in this component. It
        allows to instantiate a Db Adapter that requires no database at all and acts as an
        <acronym class="acronym">SQL</acronym> and result stack which is used by the <acronym class="acronym">API</acronym> methods.
    </p>

    <div class="section" id="zend.test.phpunit.db.quickstart"><div class="info"><h1 class="title">Quickstart</h1></div>
    

    <div class="section" id="zend.test.phpunit.db.quickstart.testcase"><div class="info"><h1 class="title">Setup a Database TestCase</h1></div>
        

        <p class="para">
            We are now writting some database tests for the Bug Database example in the
            <span class="classname">Zend_Db_Table</span> documentation. First we begin to test that
            inserting a new bug is actually saved in the database correctly. First we have to
            setup a test-class that extends
            <span class="classname">Zend_Test_PHPUnit_DatabaseTestCase</span>. This class extends the
            PHPUnit Database Extension, which in turn extends the basic
            <span class="classname">PHPUnit_Framework_TestCase</span>. A database testcase contains two
            abstract methods that have to be implemented, one for the database connection and
            one for the initial dataset that should be used as seed or fixture.
        </p>

        <blockquote class="note"><p><b class="note">Note</b>: 
            <p class="para">
                You should be familiar with the PHPUnit Database extension to follow this quickstart
                easily. Although all the concepts are explained in this documentation it may be
                helpful to read the PHPUnit documentation first.
            </p>
        </p></blockquote>

        <pre class="programlisting brush: php">
class BugsTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    private $_connectionMock;

    /**
     * Returns the test database connection.
     *
     * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection
     */
    protected function getConnection()
    {
        if($this-&gt;_connectionMock == null) {
            $connection = Zend_Db::factory(...);
            $this-&gt;_connectionMock = $this-&gt;createZendDbConnection(
                $connection, &#039;zfunittests&#039;
            );
            Zend_Db_Table_Abstract::setDefaultAdapter($connection);
        }
        return $this-&gt;_connectionMock;
    }

    /**
     * @return PHPUnit_Extensions_Database_DataSet_IDataSet
     */
    protected function getDataSet()
    {
        return $this-&gt;createFlatXmlDataSet(
            dirname(__FILE__) . &#039;/_files/bugsSeed.xml&#039;
        );
    }
}
</pre>


        <p class="para">
            Here we create the database connection and seed some data into the database. Some
            important details should be noted on this code:
        </p>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                    You cannot directly return a <span class="classname">Zend_Db_Adapter_Abstract</span>
                    from the  <span class="methodname">getConnection()</span> method, but a PHPUnit
                    specific wrapper which is generated with the
                     <span class="methodname">createZendDbConnection()</span> method.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    The database schema (tables and database) is not re-created on every
                    testrun. The database and tables have to be created manually before running
                    the tests.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    Database tests by default truncate the data during
                     <span class="methodname">setUp()</span> and then insert the seed data which is
                    returned from the  <span class="methodname">getDataSet()</span> method.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    DataSets have to implement the interface
                    <span class="classname">PHPUnit_Extensions_Database_DataSet_IDataSet</span>.
                    There is a wide range of <acronym class="acronym">XML</acronym> and YAML configuration file
                    types included in PHPUnit which allows to specifiy how the tables and datasets
                    should look like and you should look into the PHPUnit documentation to get the
                    latest information on these dataset specifications.
                </p>
            </li>
        </ul>
    </div>

    <div class="section" id="zend.test.phpunit.db.quickstart.dataset"><div class="info"><h1 class="title">Specify a seed dataset</h1></div>
        

        <p class="para">
            In the previous setup for the database testcase we have specified a seed file for the
            database fixture. We now create this file specified in the Flat <acronym class="acronym">XML</acronym>
            format:
        </p>

        <pre class="programlisting brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;dataset&gt;
    &lt;zfbugs bug_id=&quot;1&quot; bug_description=&quot;system needs electricity to run&quot;
        bug_status=&quot;NEW&quot; created_on=&quot;2007-04-01 00:00:00&quot;
        updated_on=&quot;2007-04-01 00:00:00&quot; reported_by=&quot;goofy&quot;
        assigned_to=&quot;mmouse&quot; verified_by=&quot;dduck&quot; /&gt;
    &lt;zfbugs bug_id=&quot;2&quot; bug_description=&quot;Implement Do What I Mean function&quot;
        bug_status=&quot;VERIFIED&quot; created_on=&quot;2007-04-02 00:00:00&quot;
        updated_on=&quot;2007-04-02 00:00:00&quot; reported_by=&quot;goofy&quot;
        assigned_to=&quot;mmouse&quot; verified_by=&quot;dduck&quot; /&gt;
    &lt;zfbugs bug_id=&quot;3&quot; bug_description=&quot;Where are my keys?&quot; bug_status=&quot;FIXED&quot;
        created_on=&quot;2007-04-03 00:00:00&quot; updated_on=&quot;2007-04-03 00:00:00&quot;
        reported_by=&quot;dduck&quot; assigned_to=&quot;mmouse&quot; verified_by=&quot;dduck&quot; /&gt;
    &lt;zfbugs bug_id=&quot;4&quot; bug_description=&quot;Bug no product&quot; bug_status=&quot;INCOMPLETE&quot;
        created_on=&quot;2007-04-04 00:00:00&quot; updated_on=&quot;2007-04-04 00:00:00&quot;
        reported_by=&quot;mmouse&quot; assigned_to=&quot;goofy&quot; verified_by=&quot;dduck&quot; /&gt;
&lt;/dataset&gt;
</pre>


        <p class="para">
            We will work with this four entries in the database table &quot;zfbugs&quot; in the next
            examples. The required MySQL schema for this example is:
        </p>

        <pre class="programlisting brush: sql">
CREATE TABLE IF NOT EXISTS `zfbugs` (
    `bug_id` int(11) NOT NULL auto_increment,
    `bug_description` varchar(100) default NULL,
    `bug_status` varchar(20) default NULL,
    `created_on` datetime default NULL,
    `updated_on` datetime default NULL,
    `reported_by` varchar(100) default NULL,
    `assigned_to` varchar(100) default NULL,
    `verified_by` varchar(100) default NULL,
PRIMARY KEY  (`bug_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;
</pre>

    </div>

    <div class="section" id="zend.test.phpunit.db.quickstart.initial-tests"><div class="info"><h1 class="title">A few initial database tests</h1></div>
        

        <p class="para">
            Now that we have implemented the two required abstract methods of the
            <span class="classname">Zend_Test_PHPUnit_DatabaseTestCase</span> and specified the seed
            database content, which will be re-created for each new test, we can go about to make
            our first assertion. This will be a test to insert a new bug.
        </p>

        <pre class="programlisting brush: php">
class BugsTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    public function testBugInsertedIntoDatabase()
    {
        $bugsTable = new Bugs();

        $data = array(
            &#039;created_on&#039;      =&gt; &#039;2007-03-22 00:00:00&#039;,
            &#039;updated_on&#039;      =&gt; &#039;2007-03-22 00:00:00&#039;,
            &#039;bug_description&#039; =&gt; &#039;Something wrong&#039;,
            &#039;bug_status&#039;      =&gt; &#039;NEW&#039;,
            &#039;reported_by&#039;     =&gt; &#039;garfield&#039;,
            &#039;verified_by&#039;     =&gt; &#039;garfield&#039;,
            &#039;assigned_to&#039;     =&gt; &#039;mmouse&#039;,
        );

        $bugsTable-&gt;insert($data);

        $ds = new Zend_Test_PHPUnit_Db_DataSet_QueryDataSet(
            $this-&gt;getConnection()
        );
        $ds-&gt;addTable(&#039;zfbugs&#039;, &#039;SELECT * FROM zfbugs&#039;);

        $this-&gt;assertDataSetsEqual(
            $this-&gt;createFlatXmlDataSet(dirname(__FILE__)
                                      . &quot;/_files/bugsInsertIntoAssertion.xml&quot;),
            $ds
        );
    }
}
</pre>


        <p class="para">
            Now up to the  <span class="methodname">$bugsTable-&gt;insert($data);</span> everything looks
            familiar. The lines after that contain the assertion methodname. We want to verify
            that after inserting the new bug the database has been updated correctly with the
            given data. For this we create a
            <span class="classname">Zend_Test_PHPUnit_Db_DataSet_QueryDataSet</span> instance and give
            it a database connection. We will then tell this dataset that it contains a table
            &quot;zfbugs&quot; which is given by an <acronym class="acronym">SQL</acronym> statement. This current/actual
            state of the database is compared to the expected database state which is contained in
            another <acronym class="acronym">XML</acronym> file &quot;bugsInsertIntoAssertions.xml&quot;. This
            <acronym class="acronym">XML</acronym> file is a slight deviation from the one given above and contains
            another row with the expected data:
        </p>

        <pre class="programlisting brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;dataset&gt;
    &lt;!-- previous 4 rows --&gt;
    &lt;zfbugs bug_id=&quot;5&quot; bug_description=&quot;Something wrong&quot; bug_status=&quot;NEW&quot;
        created_on=&quot;2007-03-22 00:00:00&quot; updated_on=&quot;2007-03-22 00:00:00&quot;
        reported_by=&quot;garfield&quot; assigned_to=&quot;mmouse&quot; verified_by=&quot;garfield&quot; /&gt;
&lt;/dataset&gt;
</pre>


        <p class="para">
            There are other ways to assert that the current database state equals an expected
            state. The &quot;Bugs&quot; table in the example already knows a lot about its inner state, so
            why not use this to our advantage? The next example will assert that deleting from
            the database is possible:
        </p>

        <pre class="programlisting brush: php">
class BugsTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    public function testBugDelete()
    {
        $bugsTable = new Bugs();

        $bugsTable-&gt;delete(
            $bugsTable-&gt;getAdapter()-&gt;quoteInto(&quot;bug_id = ?&quot;, 4)
        );

        $ds = new Zend_Test_PHPUnit_Db_DataSet_DbTableDataSet();
        $ds-&gt;addTable($bugsTable);

        $this-&gt;assertDataSetsEqual(
            $this-&gt;createFlatXmlDataSet(dirname(__FILE__)
                                      . &quot;/_files/bugsDeleteAssertion.xml&quot;),
            $ds
        );
    }
}
</pre>


        <p class="para">
            We have created a <span class="classname">Zend_Test_PHPUnit_Db_DataSet_DbTableDataSet</span>
            dataset here, which takes any <span class="classname">Zend_Db_Table_Abstract</span> instance
            and adds it to the dataset with its table name, in this example &quot;zfbugs&quot;. You could
            add several tables more if you wanted using the method
             <span class="methodname">addTable()</span> if you want to check for expected database state
            in more than one table.
        </p>

        <p class="para">
            Here we only have one table and check against an expected database state in
            &quot;bugsDeleteAssertion.xml&quot; which is the original seed dataset without the row with id
            4.
        </p>

        <p class="para">
            Since we have only checked that two specific tables (not datasets) are equal in the
            previous examples we should also look at how to assert that two tables are equal.
            Therefore we will add another test to our TestCase which verifies updating behaviour
            of a dataset.
        </p>

        <pre class="programlisting brush: php">
class BugsTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    public function testBugUpdate()
    {
        $bugsTable = new Bugs();

        $data = array(
            &#039;updated_on&#039;      =&gt; &#039;2007-05-23&#039;,
            &#039;bug_status&#039;      =&gt; &#039;FIXED&#039;
        );

        $where = $bugsTable-&gt;getAdapter()-&gt;quoteInto(&#039;bug_id = ?&#039;, 1);

        $bugsTable-&gt;update($data, $where);

        $rowset = $bugsTable-&gt;fetchAll();

        $ds        = new Zend_Test_PHPUnit_Db_DataSet_DbRowset($rowset);
        $assertion = $this-&gt;createFlatXmlDataSet(
            dirname(__FILE__) . &#039;/_files/bugsUpdateAssertion.xml&#039;
        );
        $expectedRowsets = $assertion-&gt;getTable(&#039;zfbugs&#039;);

        $this-&gt;assertTablesEqual(
            $expectedRowsets, $ds
        );
    }
}
</pre>


        <p class="para">
            Here we create the current database state from a
            <span class="classname">Zend_Db_Table_Rowset_Abstract</span> instance in conjunction with
            the  <span class="methodname">Zend_Test_PHPUnit_Db_DataSet_DbRowset($rowset)</span> instance
            which creates an internal data-representation of the rowset. This can again be
            compared against another data-table by using the
             <span class="methodname">$this-&gt;assertTablesEqual()</span> assertion.
        </p>
    </div>
</div>
    <div class="section" id="zend.test.phpunit.db.testing"><div class="info"><h1 class="title">Usage, API and Extensions Points</h1></div>
    

    <p class="para">
        The Quickstart already gave a good introduction on how database testing can be done using
        PHPUnit and the Zend Framework. This section gives an overview over the
        <acronym class="acronym">API</acronym> that the <span class="classname">Zend_Test_PHPUnit_Db</span> component comes
        with and how it works internally.
    </p>

    <blockquote class="note"><p><b class="note">Note</b>: <span class="info"><b>Some Remarks on Database Testing</b><br /></span>
        

        <p class="para">
            Just as the Controller TestCase is testing an application at an integration level, the
            Database TestCase is an integration testing method. Its using several different
            application layers for testing purposes and therefore should be consumed with caution.
        </p>

        <p class="para">
            It should be noted that testing domain and business logic with integration tests such
            as Zend Framework&#039;s Controller and Database TestCases is a bad practice. The purpose of
            an Integration test is to check that several parts of an application work smoothly when
            wired together. These integration tests do not replace the need for a set of unit tests
            that test the domain and business logic at a much smaller level, the isolated class.
        </p>
    </p></blockquote>

    <div class="section" id="zend.test.phpunit.db.testing.testcase"><div class="info"><h1 class="title">The Zend_Test_PHPUnit_DatabaseTestCase class</h1></div>
        

        <p class="para">
            The <span class="classname">Zend_Test_PHPUnit_DatabaseTestCase</span> class derives from the
            <span class="classname">PHPUnit_Extensions_Database_TestCase</span> which allows to setup tests
            with a fresh database fixture on each run easily. The Zend implementation offers some
            additional convenience features over the PHPUnit Database extension when it comes to
            using <span class="classname">Zend_Db</span> resources inside your tests. The workflow of a
            database test-case can be described as follows.
        </p>

        <ol type="1">
            <li class="listitem">
                <p class="para">
                    For each test PHPUnit creates a new instance of the TestCase and calls the
                     <span class="methodname">setUp()</span> method.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    The Database TestCase creates an instance of a Database Tester which handles the
                    setting up and tearing down of the database.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    The database tester collects the information on the database connection and
                    initial dataset from  <span class="methodname">getConnection()</span> and
                     <span class="methodname">getDataSet()</span> which are both abstract methods and have
                    to be implemented by any Database Testcase.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    By default the database tester truncates the tables specified in the given
                    dataset, and then inserts the data given as initial fixture.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    When the database tester has finished setting up the database, PHPUnit runs the
                    test.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    After running the test,  <span class="methodname">tearDown()</span> is called. Because
                    the database is wiped in  <span class="methodname">setUp()</span> before inserting the
                    required initial fixture, no actions are executed by the database tester at this
                    stage.
                </p>
            </li>
        </ol>

        <blockquote class="note"><p><b class="note">Note</b>: 
            <p class="para">
                The Database TestCase expects the database schema and tables to be setup correctly
                to run the tests. There is no mechanism to create and tear down database tables.
            </p>
        </p></blockquote>

        <p class="para">
            The <span class="classname">Zend_Test_PHPUnit_DatabaseTestCase</span> class has some convenience
            functions that can help writing tests that interact with the database and the database
            testing extension.
        </p>

        <p class="para">
            The next table lists only the new methods compared to the
            <span class="classname">PHPUnit_Extensions_Database_TestCase</span>, whose <a href="http://www.phpunit.de/manual/current/en/database.html" class="link external">&raquo; API is documented in
            the PHPUnit Documentation</a>.
        </p>

        <table id="zend.test.phpunit.db.testing.testcase.api-methods" class="doctable table"><div class="info"><caption><b>Zend_Test_PHPUnit_DatabaseTestCase API Methods</b></caption></div>
            

            
                <thead valign="middle">
                    <tr valign="middle">
                        <th>Method</th>
                        <th>Description</th>
                    </tr>

                </thead>


                <tbody valign="middle" class="tbody">
                    <tr valign="middle">
                        <td align="left">
                             <span class="methodname">createZendDbConnection(Zend_Db_Adapter_Abstract $connection,
                                $schema)</span>
                        </td>

                        <td align="left">
                            Create a PHPUnit Database Extension compatible Connection instance from
                            a <span class="classname">Zend_Db_Adapter_Abstract</span> instance. This method
                            should be used in for testcase setup when implementing the abstract
                             <span class="methodname">getConnection()</span> method of the database
                            testcase.
                        </td>
                    </tr>


                    <tr valign="middle">
                        <td align="left"> <span class="methodname">getAdapter()</span></td>

                        <td align="left">
                            Convenience method to access the underlying
                            <span class="classname">Zend_Db_Adapter_Abstract</span> instance which is nested
                            inside the PHPUnit database connection created with
                             <span class="methodname">getConnection()</span>.
                        </td>
                    </tr>


                    <tr valign="middle">
                        <td align="left">
                             <span class="methodname">createDbRowset(Zend_Db_Table_Rowset_Abstract $rowset,
                                $tableName = null)</span>
                        </td>

                        <td align="left">
                            Create a DataTable Object that is filled with the data from a given
                            <span class="classname">Zend_Db_Table_Rowset_Abstract</span> instance. The table
                            the rowset is connected to is chosen when <var class="varname">$tableName</var>
                            is <b><tt>NULL</tt></b>.
                        </td>
                    </tr>


                    <tr valign="middle">
                        <td align="left">
                             <span class="methodname">createDbTable(Zend_Db_Table_Abstract $table, $where = null,
                                $order = null, $count = null, $offset = null)</span>
                        </td>

                        <td align="left">
                            Create a DataTable object that represents the data contained in a
                            <span class="classname">Zend_Db_Table_Abstract</span> instance. For retrieving
                            the data  <span class="methodname">fetchAll()</span> is used, where the optional
                            parameters can be used to restrict the data table to a certain subset.
                        </td>
                    </tr>


                    <tr valign="middle">
                        <td align="left">
                             <span class="methodname">createDbTableDataSet(array $tables=array())</span>
                        </td>

                        <td align="left">
                            Create a DataSet containing the given <var class="varname">$tables</var>, an
                            array of <span class="classname">Zend_Db_Table_Abstract</span> instances.
                        </td>
                    </tr>

                </tbody>
            
        </table>

    </div>

    <div class="section" id="zend.test.phpunit.db.testing.controllerintegration"><div class="info"><h1 class="title">Integrating Database Testing with the ControllerTestCase</h1></div>
        

        <p class="para">
            Because <acronym class="acronym">PHP</acronym> does not support multiple inheritance it is not possible
            to use the Controller and Database testcases in conjunction. However you can use the
            <span class="classname">Zend_Test_PHPUnit_Db_SimpleTester</span> database tester in your
            controller test-case to setup a database enviroment fixture for each new controller
            test. The Database TestCase in general is only a set of convenience functions which can
            also be accessed and used without the test case.
        </p>

        <div class="example" id="zend.test.phpunit.db.testing.controllerintegration.example"><div class="info"><p><b>Example #1 Database integration example</b></p></div>
            

            <div class="example-contents"><p>
                This example extends the User Controller Test from the
                <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span> documentation to include
                a database setup.
            </p></div>

            <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        $this-&gt;setupDatabase();
        $this-&gt;bootstrap = array($this, &#039;appBootstrap&#039;);
        parent::setUp();
    }

    public function setupDatabase()
    {
        $db = Zend_Db::factory(...);
        $connection = new Zend_Test_PHPUnit_Db_Connection($db,
                                                      &#039;database_schema_name&#039;);
        $databaseTester = new Zend_Test_PHPUnit_Db_SimpleTester($connection);

        $databaseFixture =
                    new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(
                        dirname(__FILE__) . &#039;/_files/initialUserFixture.xml&#039;
                    );

        $databaseTester-&gt;setupDatabase($databaseFixture);
    }
}
</pre>


            <div class="example-contents"><p>
                Now the Flat <acronym class="acronym">XML</acronym> dataset &quot;initialUserFixture.xml&quot; is used to set
                the database into an initial state before each test, exactly as the DatabaseTestCase
                works internally.
            </p></div>
        </div>
    </div>
</div>
    <div class="section" id="zend.test.phpunit.db.adapter"><div class="info"><h1 class="title">Using the Database Testing Adapter</h1></div>
    

    <p class="para">
        There are times when you don&#039;t want to test parts of your application with a real database,
        but are forced to because of coupling. The <span class="classname">Zend_Test_DbAdapter</span> offers
        a convenient way to use a implementation of <span class="classname">Zend_Db_Adapter_Abstract</span>
        without having to open a database connection. Furthermore this Adapter is very easy to mock
        from within your PHPUnit testsuite, since it requires no constructor arguments.
    </p>

    <p class="para">
        The Test Adapter acts as a stack for various database results. Its order of results have to
        be userland implemented, which might be a tedious task for tests that call many different
        database queries, but its just the right helper for tests where only a handful of queries
        are executed and you know the exact order of the results that have to be returned to your
        userland code.
    </p>

    <pre class="programlisting brush: php">
$adapter   = new Zend_Test_DbAdapter();
$stmt1Rows = array(array(&#039;foo&#039; =&gt; &#039;bar&#039;), array(&#039;foo&#039; =&gt; &#039;baz&#039;));
$stmt1     = Zend_Test_DbStatement::createSelectStatement($stmt1Rows);
$adapter-&gt;appendStatementToStack($stmt1);

$stmt2Rows = array(array(&#039;foo&#039; =&gt; &#039;bar&#039;), array(&#039;foo&#039; =&gt; &#039;baz&#039;));
$stmt2     = Zend_Test_DbStatement::createSelectStatement($stmt2Rows);
$adapter-&gt;appendStatementToStack($stmt2);

$rs = $adapter-&gt;query(&#039;SELECT ...&#039;); // Returns Statement 2
while ($row = $rs-&gt;fetch()) {
    echo $rs[&#039;foo&#039;]; // Prints &quot;Bar&quot;, &quot;Baz&quot;
}
$rs = $adapter-&gt;query(&#039;SELECT ...&#039;); // Returns Statement 1
</pre>


    <p class="para">
        Behaviour of any real database adapter is simulated as much as possible such that methods
        like  <span class="methodname">fetchAll()</span>,  <span class="methodname">fetchObject()</span>,
         <span class="methodname">fetchColumn</span> and more are working for the test adapter.
    </p>

    <p class="para">
        You can also put INSERT, UPDATE and DELETE statement onto the result stack, these however
        only return a statement which allows to specifiy the result of
         <span class="methodname">$stmt-&gt;rowCount()</span>.
    </p>

    <pre class="programlisting brush: php">
$adapter = new Zend_Test_DbAdapter();
$adapter-&gt;appendStatementToStack(
    Zend_Test_DbStatement::createInsertStatement(1)
);
$adapter-&gt;appendStatementToStack(
    Zend_Test_DbStatement::createUpdateStatement(2)
);
$adapter-&gt;appendStatementToStack(
    Zend_Test_DbStatement::createDeleteStatement(10
));
</pre>


    <p class="para">
        By default the query profiler is enabled, so that you can retrieve the executed SQL
        statements and their bound parameters to check for the correctness of the execution.
    </p>

    <pre class="programlisting brush: php">
$adapter = new Zend_Test_DbAdapter();
$stmt = $adapter-&gt;query(&quot;SELECT * FROM bugs&quot;);

$qp = $adapter-&gt;getProfiler()-&gt;getLastQueryProfile();

echo $qp-&gt;getQuerY(); // SELECT * FROM bugs
</pre>


    <p class="para">
        The test adapter never checks if the query specified is really of the type SELECT, DELETE,
        INSERT or UPDATE which is returned next from the stack. The correct order of returning the
        data has to be implemented by the user of the test adapter.
    </p>

    <p class="para">
        The Test adapter also specifies methods to simulate the use of the methods
         <span class="methodname">listTables()</span>,  <span class="methodname">describeTables()</span> and
         <span class="methodname">lastInsertId()</span>. Additionally using the
         <span class="methodname">setQuoteIdentifierSymbol()</span> you can specify which
        symbol should be used for quoting, by default none is used.
    </p>
</div>
</div>
        <hr />

            <table width="100%">
                <tr>
                    <td width="25%" style="text-align: left;">
                    <a href="zend.test.phpunit.html">Zend_Test_PHPUnit</a>
                    </td>

                    <td width="50%" style="text-align: center;">
                        <div class="up"><span class="up"><a href="zend.test.html">Zend_Test</a></span><br />
                        <span class="home"><a href="manual.html">Guia de Refer&ecirc;ncia do Programador</a></span></div>
                    </td>

                    <td width="25%" style="text-align: right;">
                        <div class="next" style="text-align: right; float: right;"><a href="zend.text.html">Zend_Text</a></div>
                    </td>
                </tr>
            </table>
</td>
        <td style="font-size: smaller;" width="15%"> <style type="text/css">
#leftbar {
	float: left;
	width: 186px;
	padding: 5px;
	font-size: smaller;
}
ul.toc {
	margin: 0px 5px 5px 5px;
	padding: 0px;
}
ul.toc li {
	font-size: 85%;
	margin: 1px 0 1px 1px;
	padding: 1px 0 1px 11px;
	list-style-type: none;
	background-repeat: no-repeat;
	background-position: center left;
}
ul.toc li.header {
	font-size: 115%;
	padding: 5px 0px 5px 11px;
	border-bottom: 1px solid #cccccc;
	margin-bottom: 5px;
}
ul.toc li.active {
	font-weight: bold;
}
ul.toc li a {
	text-decoration: none;
}
ul.toc li a:hover {
	text-decoration: underline;
}
</style>
 <ul class="toc">
  <li class="header home"><a href="manual.html">Guia de Refer&ecirc;ncia do Programador</a></li>
  <li class="header up"><a href="manual.html">Guia de Refer&ecirc;ncia do Programador</a></li>
  <li class="header up"><a href="reference.html">Refer&ecirc;ncia do Zend Framework</a></li>
  <li class="header up"><a href="zend.test.html">Zend_Test</a></li>
  <li><a href="zend.test.introduction.html">Introdu&ccedil;&atilde;o</a></li>
  <li><a href="zend.test.phpunit.html">Zend_Test_PHPUnit</a></li>
  <li class="active"><a href="zend.test.phpunit.db.html">Zend_Test_PHPUnit_Db</a></li>
 </ul>
 </td>
    </tr>
</table>

<script type="text/javascript" src="../js/shCore.js"></script>
<script type="text/javascript" src="../js/shAutoloader.js"></script>
<script type="text/javascript" src="../js/main.js"></script>

</body>
</html>